package org.duiduo.exception;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.duiduo.api.constant.ResponseConsts;
import org.duiduo.api.response.RespBean;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理
 *
 * @author liangze
 * @date 2021/11/5 13:37
 */
@Slf4j
@RestControllerAdvice
public class GlobalException {

    @ExceptionHandler(SQLException.class)
    public RespBean mylSqlException(SQLException e) {
        log.error("mylSqlException: ", e);
        if (e instanceof SQLIntegrityConstraintViolationException) {
            return RespBean.error(ResponseConsts.RespErrorMsg.RESP_MSG_1.getMessage());
        }
        return RespBean.error(ResponseConsts.RespErrorMsg.RESP_MSG_2.getMessage());
    }

    @ExceptionHandler(UsernameNotFoundException.class)
    public RespBean usernameNotFoundException(UsernameNotFoundException e) {
        log.error("usernameNotFoundException: ", e);
        return RespBean.error(ResponseConsts.RespErrorMsg.RESP_MSG_3.getMessage());
    }

    @ExceptionHandler(BizException.class)
    public RespBean bizException(BizException e) {
        log.error("bizException: ", e);
        return RespBean.error(e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    public RespBean exception(Exception e) {
        log.error("Exception: ", e);
        String message = null;
        if (e instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException ve = (MethodArgumentNotValidException) e;
            message = ve.getBindingResult().getFieldError().getDefaultMessage();
        }
        if (e instanceof DataIntegrityViolationException) {
            return RespBean.error(ResponseConsts.RespErrorMsg.RESP_MSG_1.getMessage());
        }
        return RespBean.error(StrUtil.isNotBlank(message) ? message : ResponseConsts.RespErrorMsg.RESP_MSG_4.getMessage());
    }
}
